package web;

/**
 * @author Lenovo
 * @date 2022/1/5
 */
//用JFrame做页面

import com.Dao.StudentDao;
import com.bean.PageInfo;
import com.bean.Student;
import sun.swing.table.DefaultTableCellHeaderRenderer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;


//学习点4：自己实现虚线框
class JMyLabel extends JLabel {

    private Rectangle2D mfRect = new Rectangle2D.Float();
    //颜色
    private Color mfColor = new Color(255, 0, 0);

    private float[] dash1 = {5.0f};

    private BasicStroke s = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);

    public JMyLabel() {
        super();
    }

    /**
     * 重写paint方法
     */
    public void paint(Graphics g) {

        super.paint(g);

        Graphics2D g2d = (Graphics2D) g;
        //设置边框颜色
        g2d.setColor(mfColor);
        //设置边框范围
        mfRect.setRect(0, 0, getWidth() - 1, getHeight() - 1);
        //设置边框类型
        g2d.setStroke(s);

        g2d.draw(mfRect);

    }

}

public class StudentFileFrame{

    public int pageLimit = 4; //表格最多行数
    public int currentIndex=1;//当前为第1页
    private static JPanel panel = null;
    private static JFrame frame = null;
    public static  JButton sureToSearchButton = new JButton("确定");
    public static  JButton preButton = new JButton("上一页");
    public static  JButton nextButton = new JButton("下一页");
    public static  JButton exitButton = new JButton("退出");
    public static  JLabel  loadingLabel = new JMyLabel();
    public static  JTextField  searchElementArea = new  JTextField(20); //查询框
    public static JPanel tablePanel = new JPanel(new BorderLayout());
    private  String[] tages = { "学号", "姓名", "班级", "专业", "性别","学院" };
    public PageInfo pageInfo = new PageInfo();
    public static  JTable table = new JTable();
    public static    List<Student> students = new ArrayList<>();
    public static String searchSNoOrSName="";
    public static  JScrollPane jScrollPane=new JScrollPane();
    public  JPanel StudentFileFrame (int totalNum){
        //导入frame
        frame = MainFrame.returnJFrame();
        panel = new JPanel(new FlowLayout());
        //添加新的panel
        frame.add(panel);

        // panel内部设计
        //=========================== topPanel start ============================//
        JPanel topPanel = new JPanel();
        topPanel.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH, webUtil.PANEL_HEIGHT/5));
        GridLayout grid = new  GridLayout(1,2);
        topPanel.setLayout(grid);
        grid.setHgap(30);
        grid.setVgap(30);

        JLabel label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setFont(new Font("宋体",Font.BOLD,22));
        label.setText("学生档案查询系统,共"+totalNum+"条记录");
        topPanel.add(label);

        FlowLayout flowLayout = new FlowLayout();
        flowLayout.setVgap(10);
        JPanel topRightPanel = new JPanel(flowLayout);
        topRightPanel.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH/3, webUtil.PANEL_HEIGHT/6));
        loadingLabel.setHorizontalAlignment(JLabel.CENTER);
        loadingLabel.setFont(new Font("宋体",Font.BOLD,22));
        loadingLabel.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH/3, webUtil.PANEL_HEIGHT/6));
        topRightPanel.add(loadingLabel);

        topPanel.add(topRightPanel);

        panel.add(topPanel);
        //=========================== topPanel end ============================//

        //=========================== middlePanel end ============================//
        JPanel middlePanel = new JPanel();
        GridLayout grid1 = new  GridLayout(1,3);
        grid1.setHgap(20);
        grid1.setVgap(20);
        middlePanel.setLayout(grid1);
        middlePanel.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH, webUtil.PANEL_HEIGHT/5));
        JLabel label1 = new JLabel();
        label1.setHorizontalAlignment(JLabel.CENTER);
        label1.setFont(new Font("宋体",Font.BOLD,22));
        label1.setText("请输入要查询的学号/姓名:");
        middlePanel.add(label1);
            FlowLayout flow = new FlowLayout();
            flow.setHgap(45);  //设置组件之间的水平间距
            flow.setVgap(30);
            JPanel subPanel1 = new JPanel(flow);
            subPanel1.setSize(new Dimension(38, webUtil.PANEL_HEIGHT/6));

            searchElementArea.setFont(new Font("宋体",Font.BOLD,23));
            searchElementArea.setDocument(new MyDocument(20));
            searchElementArea.setPreferredSize(new Dimension (webUtil.PANEL_WIDTH/10,webUtil.PANEL_HEIGHT/12));

            subPanel1.add( searchElementArea);
            //subPanel1.setBorder(new TitledBorder(new EtchedBorder(), "测试1")); //测试用
        middlePanel.add(subPanel1);

            flow.setVgap(20);
            JPanel subPanel2 = new JPanel(flow);
            subPanel2.setSize(new Dimension(webUtil.PANEL_WIDTH/3, webUtil.PANEL_HEIGHT/6));
            sureToSearchButton.setFont(new Font("宋体",Font.BOLD,22));
            sureToSearchButton.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH/10,webUtil.PANEL_HEIGHT/11));
            subPanel2.add(sureToSearchButton);
            //subPanel2.setBorder(new TitledBorder(new EtchedBorder(), "测试2")); //测试用
        middlePanel.add(subPanel2);
        panel.add(middlePanel);
        //=========================== middlePanel end ============================//

        //=========================== table start ============================//
        tablePanel.setPreferredSize(new Dimension(webUtil.PANEL_WIDTH, webUtil.PANEL_HEIGHT*2/5));
        queryStudentByStudentDao(this.currentIndex);
        // 将表格加入到滚动条组件中
        jScrollPane = new JScrollPane(table);
        tablePanel.add(jScrollPane, BorderLayout.CENTER);
        tablePanel.setBorder(new TitledBorder(new EtchedBorder(), "")); //测试用
        panel.add(tablePanel);
        //=========================== table end ============================//


        //=========================== bottomPanel start ============================//
        JPanel bottomPanel = new JPanel();
        FlowLayout bottomFlow = new FlowLayout();
        bottomFlow.setHgap(100);  //设置组件之间的水平间距
        bottomPanel.setLayout(bottomFlow);

        preButton.setFont(new Font("宋体",Font.BOLD,22));
        preButton.setPreferredSize(new Dimension(120,60));
        bottomPanel.add(preButton);

        nextButton.setPreferredSize(new Dimension(120,60));
        nextButton.setFont(new Font("宋体",Font.BOLD,22));
        bottomPanel.add(nextButton);

        exitButton.setPreferredSize(new Dimension(120,60));
        exitButton.setFont(new Font("宋体",Font.BOLD,22));
        bottomPanel.add(exitButton);

        panel.add(bottomPanel, BorderLayout.SOUTH);
        //=========================== bottomPanel end ============================//
        //=========================== listener start  =============================//
        preButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pageInfo.setPageIndex(currentIndex);
                currentIndex=pageInfo.getPrePage();
                queryStudentByStudentDao(currentIndex);
                tablePanel.remove(jScrollPane);
                jScrollPane = new JScrollPane(table);
                tablePanel.add(jScrollPane, BorderLayout.CENTER);
            }
        });
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pageInfo.setPageIndex(currentIndex);
                currentIndex=pageInfo.getNextPage();
                tablePanel.remove(jScrollPane);
                queryStudentByStudentDao(currentIndex);
                jScrollPane = new JScrollPane(table);
                tablePanel.add(jScrollPane, BorderLayout.CENTER);
            }
        });
        sureToSearchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchSNoOrSName = searchElementArea.getText().trim();
                if(searchSNoOrSName.equals("")){
                    currentIndex=0;
                    tablePanel.remove(jScrollPane);
                    queryStudentByStudentDao(currentIndex);
                    jScrollPane = new JScrollPane(table);
                    tablePanel.add(jScrollPane, BorderLayout.CENTER);
                }else{
                    currentIndex=0;
                    Object[][] tmpPlayerInfo = queryStudentByStudentDaoInfo(searchSNoOrSName);
                    updateTable(tmpPlayerInfo);
                    tablePanel.remove(jScrollPane);
                    jScrollPane = new JScrollPane(table);
                    tablePanel.add(jScrollPane, BorderLayout.CENTER);
                }
            }
        });
        //=========================== listener end  ================================//
        return panel;
    }

    public void updateTable(Object[][]playerInfo){
        System.out.println("\n当前是第"+currentIndex+"页");
        System.out.println("更新表格中");
        if(playerInfo==null) {
            System.out.println("更新表格结束:失败");
            table = new JTable();
            searchSNoOrSName="";
            return;
        }
        table = new JTable(playerInfo, tages);
//        table.setEnabled(false); // 学习点1：这里处理了选中空白行，显示上一次多余的结果
//        table = new JTable(new DefaultTableModel(playerInfo,tages){//继承重写编辑
//            @Override
//            public boolean isCellEditable(int row, int column) {
//                return false;
//            }
//        });
        //标题居中
        DefaultTableCellHeaderRenderer hr = new DefaultTableCellHeaderRenderer();
        hr.setHorizontalAlignment(JLabel.CENTER);
        table.getTableHeader().setDefaultRenderer(hr);
        table.getTableHeader().setFont(new Font("宋体",Font.BOLD,22));

        table.setRowHeight(30);  //单元格高度
        table.getColumn("学号").setPreferredWidth(80);
        for(int i=1;i<4;i++) {
            table.getColumn(tages[i]).setPreferredWidth(15);
        }
        table.getColumn("学院").setPreferredWidth(240);
        for(int i=0;i<5;i++) { // 设置5列都能调整
            table.getColumnModel().getColumn(i).setResizable(true);
        }
        //表格内容居中
        DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
        cr.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, cr);
        table.setFont(new Font("宋体",Font.BOLD,22));
        // 设置此表视图的首选大小
        table.setPreferredScrollableViewportSize(new Dimension(webUtil.PANEL_WIDTH, webUtil.PANEL_HEIGHT*2/5));
        System.out.println("更新表格结束:成功");
        if(searchSNoOrSName.equals(""))
            sleeps(0.25,"更新结束");
        else {
            sleeps(0.25, "找到了"+searchSNoOrSName);
            searchSNoOrSName="";
        }
    }

    private void queryStudentByStudentDao(int pageIndex) {
        loadingLabel.setText("正在飞速加载加载中！！！");
        StudentDao dao = new StudentDao();
        int totalNum = dao.queryStudentCount();
        this.pageInfo.setTotal(totalNum);
        this.pageInfo.setPageIndex(pageIndex);
        this.pageInfo.setPageSize(pageLimit);
            try {
                students = dao.queryStudent(pageInfo);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(students.size()!=0) {
                    Object[][] playerInfo = new Object[students.size()][6];
                    int index = 0;
                    for (Student s : students) {
                        playerInfo[index][0] = s.getsNo();
                        playerInfo[index][1] = s.getsName();
                        playerInfo[index][2] = s.getClassNo();
                        playerInfo[index][3] = s.getSubject();
                        playerInfo[index][4] = s.getSex();
                        playerInfo[index][5] = s.getAcademy();
                        index += 1;
                    }
                    updateTable(playerInfo);
                }
            }
       // }).start();
    }

    private Object[][] queryStudentByStudentDaoInfo(String searchSNoOrSName){
        loadingLabel.setText("正在飞速加载加载中！！！");
        StudentDao dao = new StudentDao();
            try {
                students = dao.queryStudentBySnoOrSName(searchSNoOrSName);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        if(students.size()==0) {
            sleeps(0.24,"找不到"+searchSNoOrSName); return null;
        }
        Object[][]playerInfo = new Object[students.size()][6];
        int index=0;
        for(Student s:students){
            playerInfo[index][0]=s.getsNo();
            playerInfo[index][1]=s.getsName();
            playerInfo[index][2]=s.getClassNo();
            playerInfo[index][3]=s.getSubject();
            playerInfo[index][4]=s.getSex();
            playerInfo[index][5]=s.getAcademy();
            index+=1;
        }
        return playerInfo;
    }

    public void sleeps(double n,String info){//学习点2：用线程解决绘图时，JLabel需要等待JButton作用完才起作用
        new Thread(() -> {
            try {
                Thread.sleep((long) (n * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                loadingLabel.setText(info);
            }
        }).start();
    }
}
